package main

import (
	"context"
	"fmt"
	"net/http"
)

func serverAppByChan(stop <-chan struct{}) error {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		fmt.Fprintln(writer, "Hello world")
	})

	s := http.Server{
		Addr:    ":8080",
		Handler: mux,
	}

	go func() {
		//阻塞在这里
		<-stop
		fmt.Println("app close")
		s.Shutdown(context.Background())
	}()

	return s.ListenAndServe()
}

//性能监听
func serverDebugByChan(stop <-chan struct{}) error {
	s := http.Server{
		Addr:    ":8081",
		Handler: http.DefaultServeMux,
	}
	go func() {
		//阻塞在这里
		<-stop
		fmt.Println("debug close")
		s.Shutdown(context.Background())
	}()

	//return errors.New("故意报个错")
	return s.ListenAndServe()
}

func main() {
	done := make(chan error, 2)
	stop := make(chan struct{})
	go func() {
		done <- serverAppByChan(stop)
	}()
	go func() {
		done <- serverDebugByChan(stop)
	}()

	var stopped bool
	fmt.Println(stopped, cap(done))
	for i := 0; i < cap(done); i++ {
		fmt.Println(i)
		//阻塞在这里
		if err := <-done; err != nil {
			fmt.Println("error :%v", err)
		}
		if !stopped {
			stopped = true
			fmt.Println("close stop channel")
			close(stop)
		}
	}

}
